package org.shop.controller.supplier;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.GoodsClassify;
import org.shop.entity.Supplier;
import org.shop.entity.SupplierGoods;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.GoodsClassifyService;
import org.shop.service.SupplierGoodsService;
import org.shop.service.SupplierService;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import net.coobird.thumbnailator.Thumbnails;

@Controller
@RequestMapping("supplier")
public class SupplierGoodsController {
	
	private static Logger logger = LogManager.getLogger(SupplierGoodsController.class);
	@Autowired
	private SupplierGoodsService supplierGoodsService;
	@Autowired
    private GoodsClassifyService goodsClassifyService;
	@Autowired
	private SupplierService supplierService;
	
	/**
     * 获取供应商商品列表
     * @param req
     * @return
     */
    @RequestMapping("getSupplierGoodsList")
    @ResponseBody
    public Map<String, Object> getShopGoodsList(HttpServletRequest req){
        Map<String, Object> map = new HashMap<String, Object>();
        String currentPage = req.getParameter("offset");
        String pageSize = req.getParameter("limit");
        String supplierGoodsName = req.getParameter("supplierGoodsName");
        //获取登录人用户信息
        MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", Integer.parseInt(currentPage));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("supplierGoodsName", supplierGoodsName);
            paramMap.put("userId", ud.getUserId());
            map = supplierGoodsService.getSupplierGoodsList(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return map;
    }
    /**
	 * 获取一级所有分类
	 * @param req
	 * @return
	 */
	@RequestMapping("getGoodsClassifyList")
	@ResponseBody
	public List<GoodsClassify> getGoodsClassifyList(HttpServletRequest req){
		Map<String,Object> paramMap = new HashMap<String,Object>();
		List<GoodsClassify> list = null;
		try {
			paramMap.put("parentIdIsNUll", "2");
			list = goodsClassifyService.getGoodsClassifyList(paramMap);
		}catch(Exception e){
			list = null ;
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return list;
	}
	
    /**
     * 发布商品（店铺）
     * @param req
     * @return
     */
    @RequestMapping("addSupplierGoods")
    @ResponseBody
    public Map<String, Object> addSupplierGoods(HttpServletRequest req){
        Map<String, Object> map=new HashMap<String, Object>();
        String photoStr="";
        String mainPhotoStr="";
        FTPClient ftpClient =null;
        InputStream is = null;
        try{
            //创建一个通用的多部分解析器
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;

            String supplierGoodsName = multiRequest.getParameter("supplierGoodsName");
            String classifyId1 = multiRequest.getParameter("classifyId1");
            String supplierGoodsStock = multiRequest.getParameter("supplierGoodsStock");
            String supplierGoogsWeight = multiRequest.getParameter("supplierGoodsWeight");
            String supplierGoodsSize = multiRequest.getParameter("supplierGoodsSize");
            String supplierGoodsPrice = multiRequest.getParameter("supplierGoodsPrice");
            String supplierGoodsIntro = multiRequest.getParameter("supplierGoodsIntro");
            String str=supplierGoodsName+supplierGoodsSize+supplierGoodsIntro;
            String textBlackList=CommonUtil.getPropertiesParam("textBlackList");
            for(String textBlack:textBlackList.split(",")){
                if(str.contains(textBlack)){
                    map.put("state", 2);
                    map.put("msg", "文字不合法");
                    return map;
                }
            }
            //判断 request 是否有文件上传,即多部分请求
            if(multipartResolver.isMultipart(req)){
                //取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                //创建ftp链接
                String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
                ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
                while(iter.hasNext()){
                    String name=iter.next();
                    if(name.equals("supplierGoodsMainPhoto")){
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        is=file.getInputStream();
                                        ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                        //按照比例进行缩小和放大
                                        Thumbnails.of(file.getInputStream()).size(120,120).toOutputStream(bos);
                                        is = new ByteArrayInputStream(bos.toByteArray());
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        mainPhotoStr+=ftp_photoDirectory+"/"+myFileName;
                                    }
                                }
                            }
                        }
                    }else{
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        //按照比例进行缩小和放大
                                        is=file.getInputStream();
                                        int len=is.available();
                                        ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                        if(len/1024>600) {//kb
                                        	//按照比例进行缩小和放大
                                            Thumbnails.of(is).scale(0.2f).toOutputStream(bos);
                                            is = new ByteArrayInputStream(bos.toByteArray());
                                        }
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        if("".equals(photoStr)){
                                            photoStr+=ftp_photoDirectory+"/"+myFileName;
                                        }else{
                                            photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                Supplier supplier=supplierService.findSupplierByUserId(ud.getUserId());
                SupplierGoods supplierGoods=new SupplierGoods();
                supplierGoods.setSupplierGoodsName(supplierGoodsName);
                supplierGoods.setSupplierGoodsImage(photoStr);
                supplierGoods.setSupplierGoodsThums(mainPhotoStr);
                supplierGoods.setSupplierGoodsPrice(new BigDecimal(supplierGoodsPrice));
                supplierGoods.setClassifyId1(Long.parseLong(classifyId1));
                supplierGoods.setSupplierGoodsStock(Integer.parseInt(supplierGoodsStock));
                supplierGoods.setSupplierGoogsWeight(supplierGoogsWeight);
                supplierGoods.setSupplierGoodsSize(supplierGoodsSize);
                supplierGoods.setSupplierGoodsIntro(supplierGoodsIntro);
                supplierGoods.setSupplierId(supplier.getSupplierId());
                supplierGoods.setUserId(ud.getUserId());
                supplierGoods.setState((byte)1);
                supplierGoods.setCreateDate(new Date());
                supplierGoodsService.insertSelective(supplierGoods);
                map.put("state", 1);
                map.put("msg", "发布成功");
            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
            map.put("msg", "发布失败");
        }finally {
        	try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                is=null;
            }
        }
        return map;
    }

    /**
     * 商品修改
     * @param req
     * @return
     */
    @RequestMapping("updateSupplierGoods")
    @ResponseBody
    public Map<String, Object> updateSupplierGoods(HttpServletRequest req){
        Map<String, Object> map=new HashMap<String, Object>();
        String photoStr="";
        String mainPhotoStr="";
        FTPClient ftpClient =null;
        InputStream is = null;
        try{
            //创建一个通用的多部分解析器
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
            String supplierGoodsName = multiRequest.getParameter("supplierGoodsName");
            String classifyId1 = multiRequest.getParameter("classifyId1");
            String supplierGoodsStock = multiRequest.getParameter("supplierGoodsStock");
            String supplierGoodsWeight = multiRequest.getParameter("supplierGoodsWeight");
            String supplierGoodsSize = multiRequest.getParameter("supplierGoodsSize");
            String supplierGoodsPrice = multiRequest.getParameter("supplierGoodsPrice");
            String supplierGoodsIntro = multiRequest.getParameter("supplierGoodsIntro");
            String supplierGoodsId = multiRequest.getParameter("supplierGoodsId");

            String goodsMainText = multiRequest.getParameter("goodsMainText");
            String[] goodsTexts = multiRequest.getParameterValues("goodsText");
            mainPhotoStr=goodsMainText;
            for(String goodsText:goodsTexts){
                if(!StringUtils.isEmpty(goodsText)){
                    if(StringUtils.isEmpty(photoStr)){
                        photoStr=goodsText;
                    }else{
                        photoStr+=","+goodsText;
                    }
                }
            }
            String str=supplierGoodsName+supplierGoodsSize+supplierGoodsIntro;
            String textBlackList=CommonUtil.getPropertiesParam("textBlackList");
            for(String textBlack:textBlackList.split(",")){
                if(str.contains(textBlack)){
                    map.put("state", 2);
                    map.put("msg", "文字不合法");
                    return map;
                }
            }
            //判断 request 是否有文件上传,即多部分请求
            if(multipartResolver.isMultipart(req)){
                //取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                //创建ftp链接
                String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
                ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
                while(iter.hasNext()){
                    String name=iter.next();
                    if(name.equals("goodsMainPhoto")){
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                    	myFileName=FtpUtil2.generateFileName(myFileName);
                                        is=file.getInputStream();
                                        ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                        //按照比例进行缩小和放大
                                        Thumbnails.of(file.getInputStream()).size(120,120).toOutputStream(bos);
                                        is = new ByteArrayInputStream(bos.toByteArray());
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        mainPhotoStr+=ftp_photoDirectory+"/"+myFileName;
                                    }
                                }
                            }
                        }
                    }else{
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                    	myFileName=FtpUtil2.generateFileName(myFileName);
                                        //按照比例进行缩小和放大
                                        is=file.getInputStream();
                                        int len=is.available();
                                        ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                        if(len/1024>600) {//kb
                                        	//按照比例进行缩小和放大
                                            Thumbnails.of(is).scale(0.2f).toOutputStream(bos);
                                            is = new ByteArrayInputStream(bos.toByteArray());
                                        }
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        if("".equals(photoStr)){
                                            photoStr+=ftp_photoDirectory+"/"+myFileName;
                                        }else{
                                            photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                SupplierGoods supplierGoods=new SupplierGoods();
                supplierGoods.setSupplierGoodsId(Long.parseLong(supplierGoodsId));
                supplierGoods.setSupplierGoodsName(supplierGoodsName);
                supplierGoods.setSupplierGoodsImage(photoStr);
                supplierGoods.setSupplierGoodsThums(mainPhotoStr);
                supplierGoods.setSupplierGoodsPrice(new BigDecimal(supplierGoodsPrice));
                supplierGoods.setClassifyId1(Long.parseLong(classifyId1));
                supplierGoods.setSupplierGoodsStock(Integer.parseInt(supplierGoodsStock));
                supplierGoods.setSupplierGoogsWeight(supplierGoodsWeight);
                supplierGoods.setSupplierGoodsSize(supplierGoodsSize);
                supplierGoods.setSupplierGoodsIntro(supplierGoodsIntro);
                supplierGoods.setUserId(ud.getUserId());
                supplierGoodsService.updateByPrimaryKeySelective(supplierGoods);
                map.put("state", 1);
                map.put("msg", "发布成功");
            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
            map.put("msg", "发布失败");
        }finally {
         	try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                is=null;
            }
        }
        return map;
    }
    
    /**
     * 通过商品ID获取商品信息
     * @param req
     * @return
     */
    @RequestMapping("getSupplierGoodsInfo")
    @ResponseBody
    public Map<String, Object> getSupplierGoodsInfo(HttpServletRequest req){
        String supplierGoodsId = req.getParameter("supplierGoodsId");
        Map<String, Object> map = null;
        try {
        	map = supplierGoodsService.getGoodsInfoBySupplierGoodsId(Long.parseLong(supplierGoodsId));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return map;
    }
    
}
